package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.exception.CustomException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.*;
import com.itheima.service.ClazzService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {
        PageHelper.startPage(clazzQueryParam.getPage(),clazzQueryParam.getPageSize());
        List<Clazz> lists=clazzMapper.list(clazzQueryParam);
        lists.forEach(list->{
            if (LocalDate.now().isAfter(list.getEndDate())) {
                list.setStatus("已结课");
            }
           else if (LocalDate.now().isBefore(list.getEndDate())) {
                list.setStatus("未开班");
            }else {
               list.setStatus("在读中");
            }
            Emp emp = empMapper.getById(list.getMasterId());
           list.setMasterName(emp.getName());
        });
        Page<Clazz> page= (Page<Clazz>) lists;

        return new PageResult<>(page.getTotal(),page.getResult());
    }

    @Override
    public void addClazz(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.addClazz(clazz);
       // empMapper.findAll();
    }

    @Override
    public Clazz findById(Integer id) {

        return clazzMapper.findById(id);
    }

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);

    }

    @Override
    public void delete(Integer id) {
        List<Student> students = studentMapper.findClazzById(id);


        if (!students.isEmpty()) {
            throw new CustomException("班级关联学生不能删除");
        } else {
            clazzMapper.delete(id);
        }
    }

    @Override
    public List<Clazz> findAll() {

        return clazzMapper.findAll();
    }
}
